<template>
  <!-- 头部 -->
  <header class="header">
    <!-- 头部的第一行 -->
    <div class="top">
      <div class="container">
        <div class="loginList">
          <p>尚品汇欢迎您！</p>
          <p v-if="!userInfo.name">
            <span>请</span>
            <router-link to="/login">登录</router-link>
            <router-link to="/register" class="register">免费注册</router-link>
          </p>
          <p v-else>
            <span>{{ userInfo.name }}</span>
            &nbsp;&nbsp;
            <span @click="logout">退出登录</span>
          </p>
        </div>
        <div class="typeList">
          <router-link to="/home">购物首页</router-link>
          <router-link to="/center">我的订单</router-link>
          <router-link to="/shopcart">我的购物车</router-link>
          <router-link to="">我的尚品汇</router-link>
          <router-link to="">尚品汇会员</router-link>
          <router-link to="">企业采购</router-link>
          <router-link to="">关注尚品汇</router-link>
          <router-link to="">合作招商</router-link>
          <router-link to="">商家后台</router-link>
        </div>
      </div>
    </div>
    <!--头部第二行 搜索区域-->
    <div class="bottom">
      <h1 class="logoArea">
        <router-link class="logo" title="尚品汇" to="/home" >
          <img src="./images/logo.png" alt="" />
        </router-link>
      </h1>
      <div class="searchArea">
        <form class="searchForm">
          <input
            v-model="keyWord"
            type="text"
            id="autocomplete"
            class="input-error input-xxlarge"
          />
          <button
            class="sui-btn btn-xlarge btn-danger"
            type="button"
            @click.prevent="goSearch"
          >
            搜索
          </button>
        </form>
      </div>
    </div>
  </header>
</template>

<script>
import { mapState } from 'vuex'
export default {
  data() {
    return {
      keyWord: ''
    }
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo
    })
  },

  methods: {
    goSearch() {
      //路由跳转并传递参数
      let locations = {
        name: 'search',
        params: { keyword: this.keyWord || undefined }
      }
      if (this.$route.query) {
        locations.query = this.$route.query
      }
      this.$router.push(locations)
    },
    // 退出登录
    async logout() {
      const result = await this.$store.dispatch('logout')
      if (!result.ok) {
        alert(result.msg)
      } else {
        // 数据已经清理
        // 跳转home
        this.$router.push({ name: 'home' })
      }
    }
  },

  created() {
    this.$bus.$on('removeKeyword', () => {
      this.keyWord = ''
    })
  }
}
</script>

<style></style>
